<script setup lang="ts">
//
import {
  getHomeBannerAPI,
  getHomeCategoryAPI,
  getHomeHotAPI,
} from '@/services/home'
import CustomNavbar from './components/CustomNavbar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import PageSkeleton from './components/PageSkeleton.vue'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import type { XtxSwiperInstance } from '@/types/component'
import { useGuessList } from '@/composables'

// 获取轮播图
let bannerList = ref<BannerItem[]>([])
const swiperRef = ref<XtxSwiperInstance>()
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
}

// 获取分类
const categorylist = ref<CategoryItem[]>([])
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryAPI()
  categorylist.value = res.result
}

// 获取分类
const hotlist = ref<HotItem[]>([])
const getHomeHotData = async () => {
  const res = await getHomeHotAPI()
  hotlist.value = res.result
}

// 是否加载中的标记
const isLoading = ref(false)

onLoad(async () => {
  isLoading.value = true
  await Promise.all([
  getHomeBannerData(),
  getHomeCategoryData(),
  getHomeHotData()
  ])
  isLoading.value = false
})

// 调用猜你喜欢组合式函数
const {guessRef,onScrolltolower} = useGuessList()

// 下拉刷新
const isTriggered = ref(false)
const onrefresherrefresh = async () => {
  isTriggered.value = true
  bannerList.value = []
  guessRef.value?.reseGuessData()
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHomeHotData(),
    //swiperRef.value?.reseSwiperData(),
    guessRef.value?.getMore()
  ])
  isTriggered.value = false
}
</script>

<template>
  <!-- 头部导航栏 -->
  <CustomNavbar />
  <scroll-view
    refresher-enabled
    :refresher-triggered="isTriggered"
    @refresherrefresh="onrefresherrefresh"
    @scrolltolower="onScrolltolower"
    class="scroll-view"
    scroll-y
  >
  <PageSkeleton v-if="isLoading"/>
    <template v-else>
      <!-- 轮播图 -->
    <XtxSwiper ref="swiperRef" :list="bannerList" />
    <!-- 分类 -->
    <CategoryPanel :list="categorylist" />
    <!-- 热门推荐 -->
    <HotPanel :list="hotlist" />
    <!-- 猜你喜欢 -->
    <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f7f7f7;
}
</style>
